/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package xmarti.vacaxm.model;



import xmarti.vacaxm.utils.HibernateUtil;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;


import org.hibernate.classic.Session;

import xmarti.vacaxm.beans.maintenance.*;
import xmarti.vacaxm.exception.ExceptionHibernateVacaxm;


/**
 *
 * @author xmarti
 */
public class ModelMaintenance extends HibernateUtil {
      
    public  <T>T getByAnimalCode( AnimalCode ac) throws ExceptionHibernateVacaxm  {        
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        T recoveredObject = null;
        try
        {                                
            Query query=session.createQuery("from "+ ac.getClass().getSimpleName()+" a where a.country=:id1 "
                  + "and a.areaCode=:id2 "
                  + "and a.controlCode=:id3 "
                  + "and a.animalCode1=:id4 "
                  + "and a.animalCode2=:id5");
            query.setParameter("id1",ac.getCountry());
            query.setParameter("id2",ac.getAreaCode());
            query.setParameter("id3",ac.getControlCode());
            query.setParameter("id4",ac.getAnimalCode1());
            query.setParameter("id5",ac.getAnimalCode2());
            recoveredObject = (T)query.uniqueResult();
        }
        catch (HibernateException he)
        {
            throw new ExceptionHibernateVacaxm(ExceptionHibernateVacaxm.ERR_SELECT);

        }   
      
        return recoveredObject ;
    }
    public List<Breed> getListBreeds() throws ExceptionHibernateVacaxm{
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        List<Breed> resultList = new ArrayList<Breed>();
        try
        {            
            resultList= session.createQuery("FROM Breed c order by c.name" ).list();
        }
        catch (HibernateException he)
        {
            throw new ExceptionHibernateVacaxm(ExceptionHibernateVacaxm.ERR_SELECT);
        }
        return resultList;
    }
    public List<Country> getListCountries() throws ExceptionHibernateVacaxm{
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        List<Country> resultList = new ArrayList<Country>();
        try
        {            
            resultList= session.createQuery("FROM Country c order by c.code" ).list();
        }
        catch (HibernateException he)
        {
            throw new ExceptionHibernateVacaxm(ExceptionHibernateVacaxm.ERR_SELECT);
        }
        return resultList;
    }
    public List<Area> getListAreas() throws ExceptionHibernateVacaxm{
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        List<Area> resultList = new ArrayList<Area>();
        try
        {            
            resultList= session.createQuery("FROM Area a order by a.code" ).list();
        }
        catch (HibernateException he)
        {
            throw new ExceptionHibernateVacaxm(ExceptionHibernateVacaxm.ERR_SELECT);
        }
        return resultList;
    }
    
    public  <T> List<T> getListAnimalActive(Class<T> entityClass,AnimalFilter f) throws ExceptionHibernateVacaxm {        
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();
            List<T> resultList = null;
            String filter = null;
            filter= this.getFilterString(f);
            try
            {                            
                if (filter!= null) {
                      resultList= session.createQuery("FROM " + entityClass.getSimpleName()+ " e where "+ filter +" and e.active=true ORDER BY e.country.code,e.controlCode,e.areaCode.code,e.animalCode1,e.animalCode2").list();    
                
                }else{
                      resultList= session.createQuery("FROM " + entityClass.getSimpleName()+ " e where e.active=true ORDER BY e.country.code,e.controlCode,e.areaCode.code,e.animalCode1,e.animalCode2").list();                   
                }
                                
            }
            catch (HibernateException he)
            {
                throw new ExceptionHibernateVacaxm(ExceptionHibernateVacaxm.ERR_SELECT);
            }
            return resultList;
        }
    public   <T> List<T> getListAnimalActive(Class<T> entityClass,AnimalFilter f, String gender) throws ExceptionHibernateVacaxm {        
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();
            List<T> resultList = null;
            String filter = null;
            filter= this.getFilterString(f);
            try
            {     
                if (filter!= null) {
                    resultList= session.createQuery("FROM " + entityClass.getSimpleName()+ " e "
                                             + " WHERE "+ filter + " and   e.active=true and e.gender='" +gender+ "'"
                                             + " ORDER BY e.country.code,"
                                                       + "e.controlCode,"
                                                       + "e.areaCode.code,"
                                                       + "e.animalCode1,"
                                                       + "e.animalCode2").list();
                }else{
                    resultList= session.createQuery("FROM " + entityClass.getSimpleName()+ " e "
                                             + " WHERE e.active=true and e.gender='" +gender+ "'"
                                             + " ORDER BY e.country.code,"
                                                       + "e.controlCode,"
                                                       + "e.areaCode.code,"
                                                       + "e.animalCode1,"
                                                       + "e.animalCode2").list();
                }
                
            }
            catch (HibernateException he)
            {
                throw new ExceptionHibernateVacaxm(ExceptionHibernateVacaxm.ERR_SELECT);
            }
            return resultList;
        }
    public   List<Cow> getListCowsActive() throws ExceptionHibernateVacaxm {        
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();
            List<Cow> resultList = null;
            try
            {            
                resultList= session.createQuery("FROM Cow e where e.active=true order by e.animalCode2").list();
            }
            catch (HibernateException he)
            {
                throw new ExceptionHibernateVacaxm(ExceptionHibernateVacaxm.ERR_SELECT);
            }
            return resultList;
        }
    
    public  <T> List<T> getListAnimal(Class<T> entityClass) throws ExceptionHibernateVacaxm {        
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();
            List<T> resultList = null;
            try
            {            
                resultList= session.createQuery("FROM " + entityClass.getSimpleName()+ " e ORDER BY e.country.code,e.controlCode,e.areaCode.code,e.animalCode1,e.animalCode2").list();
            }
            catch (HibernateException he)
            {
                throw new ExceptionHibernateVacaxm(ExceptionHibernateVacaxm.ERR_SELECT);
            }
            return resultList;
        }
    
    
    public  <T> List<T> getListAnimalNOActive(Class<T> entityClass) throws ExceptionHibernateVacaxm {        
            Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();
            List<T> resultList = null;
            try
            {            
                resultList= session.createQuery("FROM " + entityClass.getSimpleName()+ " e WHERE e.active=false ORDER BY e.country.code,e.controlCode,e.areaCode.code,e.animalCode1,e.animalCode2").list();
            }
            catch (HibernateException he)
            {
                throw new ExceptionHibernateVacaxm(ExceptionHibernateVacaxm.ERR_SELECT);
            }
            return resultList;
        }
    public long getNumberAnimalsActive(Class entityClass){
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();        
        return (Long)session.createQuery("SELECT count(e.id) FROM " + entityClass.getSimpleName()+ " e WHERE e.active=True").uniqueResult();        
    }
    public long getNumberAnimalsActive(Class entityClass, String gender){
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();        
        return (Long)session.createQuery("SELECT count(e.id) FROM " + entityClass.getSimpleName()+ " e WHERE e.active=True and e.gender='" +gender+"'").uniqueResult();        
    }
    private String getFilterString(AnimalFilter f){
        String filter=" ";
        if (f.getFather()!= null){
            filter = filter + " e.father=" +f.getFather().getId(); 
        }
        if (f.getMother()!=null){
            if (filter!=" ") filter=filter+ " and";
            filter = filter + " e.mother=" +f.getMother().getId(); 
        }
        if (f.getOrigin()!= null){
            if (filter!=" ") filter=filter+ " and";
            filter = filter + " e.origin=" +f.getOrigin().getId(); 
        }
        if (f.getDestination()!= null){
            if (filter!=" ") filter=filter+ " and";
            filter = filter + " e.destination=" +f.getDestination().getId();
        }
        if (f.isAgeFilter()){                     
            
            if (filter!=" ") filter=filter+ " and";
            filter= filter+ " TIMESTAMPDIFF(YEAR,e.birthDate,curDate()) between "+ f.getAgeStart() +" and " +f.getAgeEnd();            
        }
        if (f.isDateHighFilter()){
            if (filter!=" ") filter=filter+ " and";
            
            filter= filter+ " e.highDate between '"+ new java.sql.Date(f.getDateHighStart().getTime()) +"' and '" + new java.sql.Date(f.getDateHighEnd().getTime())+ "'"; 
            
            
        }
        if (f.isDateLowFilter()){
            if (filter!=" ") filter=filter+ " and";
            filter= filter+ " e.dateLow beetwen '" + new java.sql.Date(f.getDateLowStart().getTime()) +"' and '" +new java.sql.Date(f.getDateLowEnd().getTime())+ "'";
        }
        System.out.println(filter);
       if (filter!=" ") return filter;                    
       return null;
    }
    
    public int add(Breed object) throws ExceptionHibernateVacaxm {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
                int state=0;                
		try{			                        
                        session.save(object);                                                
			state= object.getId();
                        session.getTransaction().commit();
                        
		}catch (Exception e){			
			session.getTransaction().rollback();		
                        if (e.getCause().toString().contains("name_UNIQUE")){
                            throw new ExceptionHibernateVacaxm(ExceptionHibernateVacaxm.ERR_INSERT_NAME_UNIQUE);
                        }else{
                            throw new ExceptionHibernateVacaxm(ExceptionHibernateVacaxm.ERR_INSERT);			
                        }                        
		}		
		return state;
	}
    public int add(Country object) throws ExceptionHibernateVacaxm {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
                int state=0;                
		try{			                        
                        session.save(object);                                                
			state= object.getId();
                        session.getTransaction().commit();
                        
		}catch (Exception e){			
			session.getTransaction().rollback();		
                        if (e.getCause().toString().contains("name_UNIQUE")){
                            throw new ExceptionHibernateVacaxm(ExceptionHibernateVacaxm.ERR_INSERT_NAME_UNIQUE);
                        }else{
                            throw new ExceptionHibernateVacaxm(ExceptionHibernateVacaxm.ERR_INSERT);			
                        }                        
		}		
		return state;
	}
    
        public int add(Area object) throws ExceptionHibernateVacaxm {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
                int state=0;                
		try{			                        
                        session.save(object);                                                
			state= object.getId();
                        session.getTransaction().commit();
                        
		}catch (Exception e){			
			session.getTransaction().rollback();		
                        if (e.getCause().toString().contains("name_UNIQUE")){
                            throw new ExceptionHibernateVacaxm(ExceptionHibernateVacaxm.ERR_INSERT_NAME_UNIQUE);
                        }else{
                            throw new ExceptionHibernateVacaxm(ExceptionHibernateVacaxm.ERR_INSERT);			
                        }                        
		}		
		return state;
	}
}
